﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using log4net;
using McsUtility;

namespace MinerManager.Forms
{
	public partial class MinerWallet : DevExpress.XtraEditors.XtraForm
	{
		ILog logger = LogManager.GetLogger(typeof(Program));
		private Common.AgentComponent Agent = null;

		public event EventHandler<EventArgs> OnClose;

		private ContextMenuStrip RightContextMenu = null;
		private string ContextMenuSourceName = string.Empty;//点击ContextMenuStrip的来源控件名称
		private int SelectedCurrencyId = 0;//选中的币种Id

		public MinerWallet(Common.AgentComponent agent)
		{
			InitializeComponent();
			this.Agent = agent;
		}

		#region 窗体事件

		private void MinerWallet_Load(object sender, EventArgs e)
		{
			this.Agent.OnGetCurrencysReceive += new EventHandler<ByteEventArgs>(Agent_OnGetCurrencys);
			this.Agent.OnDeletePoolReceive += new EventHandler<ByteEventArgs>(Agent_OnDeletePoolReceive);
			this.Agent.OnDeleteWalletReceive += new EventHandler<ByteEventArgs>(Agent_OnDeleteWalletReceive);

			LoadContextMenu();
			RequestRefresh();
		}

		private void MinerWallet_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.Agent.OnGetCurrencysReceive -= new EventHandler<ByteEventArgs>(Agent_OnGetCurrencys);
			this.Agent.OnDeletePoolReceive -= new EventHandler<ByteEventArgs>(Agent_OnDeletePoolReceive);
			this.Agent.OnDeleteWalletReceive -= new EventHandler<ByteEventArgs>(Agent_OnDeleteWalletReceive);

			OnClose?.Invoke(this, new EventArgs());
		}

		private void LoadContextMenu()
		{
			this.RightContextMenu = new ContextMenuStrip();

			#region 复制

			Action<object, EventArgs> copyClick = delegate (object obj, EventArgs args)
			{
				string value = WalletListGridView.GetFocusedRowCellValue(WalletListGridView.FocusedColumn).ToString();
				Clipboard.SetDataObject(value);
			};

			ToolStripMenuItem itemCopy = new ToolStripMenuItem("复制");
			itemCopy.Click += new EventHandler(copyClick);
			this.RightContextMenu.Items.Add(itemCopy);

			#endregion

			#region 修改事件

			Action<object, EventArgs> editClick = delegate (object obj, EventArgs args)
			{
				if (this.ContextMenuSourceName.Equals("WalletList", StringComparison.CurrentCultureIgnoreCase))
				{
					int[] selectedRows = WalletListGridView.GetSelectedRows();
					int selectedIndex = selectedRows.Length > 0 ? selectedRows[0] : -1;
					if (selectedIndex >= 0)
					{
						List< Models.AddressModel> infos = WalletList.DataSource as List<Models.AddressModel>;
						if (infos.Count > 0)
						{
							WalletUpdate form = new WalletUpdate(this.Agent, infos[selectedIndex]);
							form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
							form.ShowDialog();
						}
					}
				}

				if (this.ContextMenuSourceName.Equals("PoolList", StringComparison.CurrentCultureIgnoreCase))
				{
					int[] selectedRows = PoolListGridView.GetSelectedRows();
					int selectedIndex = selectedRows.Length > 0 ? selectedRows[0] : -1;
					if (selectedIndex >= 0)
					{
						List<Models.AddressModel> infos = PoolList.DataSource as List<Models.AddressModel>;
						if (infos.Count > 0)
						{
							PoolUpdate form = new PoolUpdate(this.Agent, infos[selectedIndex]);
							form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
							form.ShowDialog();
						}
					}
				}
			};

			ToolStripMenuItem itemEdit = new ToolStripMenuItem("修改");
			itemEdit.Click += new EventHandler(editClick);
			this.RightContextMenu.Items.Add(itemEdit);

			#endregion

			#region 删除事件

			Action<object, EventArgs> deleteClick = delegate (object obj, EventArgs args)
			{
				if (this.ContextMenuSourceName.Equals("WalletList", StringComparison.CurrentCultureIgnoreCase))
				{
					if (MessageBox.Show("确定要删除选择的钱包吗？\r\n删除后将不可恢复。", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
					{
						//发送数据
						if (this.Agent.IsStarted)
						{
							int[] selectedRows = WalletListGridView.GetSelectedRows();
							int selectedIndex = selectedRows.Length > 0 ? selectedRows[0] : -1;
							if (selectedIndex >= 0)
							{
								List<Models.AddressModel> infos = WalletList.DataSource as List<Models.AddressModel>;
								if (infos.Count > 0)
								{
									McsUtility.Models.WalletsModel info = new McsUtility.Models.WalletsModel
									{
										ID = infos[selectedIndex].Id,
										Address = infos[selectedIndex].Address,
										Remark = infos[selectedIndex].Remark
									};

									byte[] bytes = ProtocolHelper.WritePackage(ProtoType.MinerManagerDelWallets, info);
									this.Agent.AgentSend(bytes);
								}
							}
							else
							{
								MessageBox.Show("未获取到有效的选取行信息。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
							}
						}
						else
						{
							if (MessageBox.Show("与服务器的链接断开，请重新登录系统。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
								Utility.Forms.FormClose(this);
						}
					}
				}

				if (this.ContextMenuSourceName.Equals("PoolList", StringComparison.CurrentCultureIgnoreCase))
				{
					if (MessageBox.Show("确定要删除选择的矿池吗？\r\n删除后将不可恢复。", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
					{
						//发送数据
						if (this.Agent.IsStarted)
						{
							int[] selectedRows = PoolListGridView.GetSelectedRows();
							int selectedIndex = selectedRows.Length > 0 ? selectedRows[0] : -1;
							if (selectedIndex >= 0)
							{
								List<Models.AddressModel> infos = PoolList.DataSource as List<Models.AddressModel>;
								if (infos.Count > 0)
								{
									McsUtility.Models.WalletsModel info = new McsUtility.Models.WalletsModel
									{
										ID = infos[selectedIndex].Id,
										Address = infos[selectedIndex].Address,
										Remark = infos[selectedIndex].Remark
									};

									byte[] bytes = ProtocolHelper.WritePackage(ProtoType.MinerManagerDelOrePools, info);
									this.Agent.AgentSend(bytes);
								}
							}
							else
							{
								MessageBox.Show("未获取到有效的选取行信息。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
							}
						}
						else
						{
							if (MessageBox.Show("与服务器的链接断开，请重新登录系统。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
								Utility.Forms.FormClose(this);
						}
					}
				}
			};

			ToolStripMenuItem itemDelete = new ToolStripMenuItem("删除");
			itemDelete.Click += new EventHandler(deleteClick);
			this.RightContextMenu.Items.Add(itemDelete);

			#endregion
		}

		#endregion

		#region Agent事件

		private void Agent_OnGetCurrencys(object sender, ByteEventArgs e)
		{
			Common.Data.UserCurrency = ProtocolHelper.ReadPackageBody<List<McsUtility.Models.CurrencysModel>>(e.Bytes);
			LoadData();
		}

		private void Agent_OnDeletePoolReceive(object sender, ByteEventArgs e)
		{
			McsUtility.Models.ResultModel result = ProtocolHelper.ReadPackageBody<McsUtility.Models.ResultModel>(e.Bytes);
			if (result.success)
				RequestRefresh();
			else
				MessageBox.Show("矿池删除失败，" + result.message + "。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		private void Agent_OnDeleteWalletReceive(object sender, ByteEventArgs e)
		{
			McsUtility.Models.ResultModel result = ProtocolHelper.ReadPackageBody<McsUtility.Models.ResultModel>(e.Bytes);
			if (result.success)
				RequestRefresh();
			else
				MessageBox.Show("钱包删除失败，" + result.message + "。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		#endregion

		#region TopMenu按钮点击事件

		private void TopMenu_WalletAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
		{
			WalletInsert form = new WalletInsert(this.Agent, this.SelectedCurrencyId);
			form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
			form.ShowDialog();
		}

		private void TopMenu_PoolAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
		{
			PoolInsert form = new PoolInsert(this.Agent, this.SelectedCurrencyId);
			form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
			form.ShowDialog();
		}

		private void TopMenu_Refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
		{
			RequestRefresh();
		}

		private void TopMenu_SyncLtcc_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
		{
			Forms.MinerSyncLtcc form = new MinerSyncLtcc(this.Agent);
			form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
			form.ShowDialog();
		}

		#endregion

		#region GridView的鼠标点击事件

		private void CurrencyList_MouseClick(object sender, MouseEventArgs e)
		{
			//DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo view = CurrencyListGridView.CalcHitInfo(e.Location);

			//if (e.Button == MouseButtons.Right && view.InRow)
			//{
			//	this.RightContextMenu.Items[0].Visible = false;
			//	this.ContextMenuSourceName = "CurrencyList";
			//	this.RightContextMenu.Show(CurrencyList, e.Location);
			//}
		}

		private void WalletList_MouseClick(object sender, MouseEventArgs e)
		{
			DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo view = WalletListGridView.CalcHitInfo(e.Location);

			if (e.Button == MouseButtons.Right && view.InRow)
			{
				this.ContextMenuSourceName = "WalletList";

				var column = WalletListGridView.FocusedColumn;
				switch (column.Name.ToLower())
				{
					case "walletlist_currencyname":
						this.RightContextMenu.Items[0].Visible = true;
						this.RightContextMenu.Items[0].Text = "复制币种";
						break;
					case "walletlist_address":
						this.RightContextMenu.Items[0].Visible = true;
						this.RightContextMenu.Items[0].Text = "复制钱包";
						break;
					case "walletlist_remark":
						this.RightContextMenu.Items[0].Visible = true;
						this.RightContextMenu.Items[0].Text = "复制备注";
						break;
					default:
						this.RightContextMenu.Items[0].Visible = false;
						break;
				}

				this.RightContextMenu.Show(WalletList, e.Location);
			}
		}

		private void PoolList_MouseClick(object sender, MouseEventArgs e)
		{
			DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo view = PoolListGridView.CalcHitInfo(e.Location);

			if (e.Button == MouseButtons.Right && view.InRow)
			{
				this.ContextMenuSourceName = "PoolList";

				var column = PoolListGridView.FocusedColumn;
				switch (column.Name.ToLower())
				{
					case "poollist_currencyname":
						this.RightContextMenu.Items[0].Visible = true;
						this.RightContextMenu.Items[0].Text = "复制币种";
						break;
					case "poollist_address":
						this.RightContextMenu.Items[0].Visible = true;
						this.RightContextMenu.Items[0].Text = "复制矿池地址";
						break;
					case "poollist_remark":
						this.RightContextMenu.Items[0].Visible = true;
						this.RightContextMenu.Items[0].Text = "复制备注";
						break;
					default:
						this.RightContextMenu.Items[0].Visible = false;
						break;
				}

				this.RightContextMenu.Show(PoolList, e.Location);
			}
		}

		#endregion

		#region void CurrencyList_Click(object sender, EventArgs e)

		private void CurrencyList_Click(object sender, EventArgs e)
		{
			List<Models.AddressModel> infosWallet = new List<Models.AddressModel>();
			List<Models.AddressModel> infosPool = new List<Models.AddressModel>();

			int[] selectedRows = CurrencyListGridView.GetSelectedRows();
			int selectedIndex = selectedRows.Length > 0 ? selectedRows[0] : -1;
			if (selectedIndex >= 0)
			{
				McsUtility.Models.CurrencysModel infoCurrency = null;
				List<Models.CurrencyModel> infosCurrency = CurrencyList.DataSource as List<Models.CurrencyModel>;
				if (infosCurrency != null)
				{
					Common.Data.UserCurrency.ForEach(info =>
					{
						if (info.ID == infosCurrency[selectedIndex].Id)
							infoCurrency = info;
					});
				}

				if (infoCurrency != null)
				{
					this.SelectedCurrencyId = infoCurrency.ID;

					for (int i = 0; i < infoCurrency.Wallets.Count; i++)
					{
						McsUtility.Models.WalletsModel infoWallet = infoCurrency.Wallets[i];
						infosWallet.Add(new Models.AddressModel
						{
							Number = (i + 1).ToString(),
							CurrencyName = infoCurrency.Remark,
							Address = infoWallet.Address,
							Remark = infoWallet.Remark
						});
					}

					for (int i = 0; i < infoCurrency.OrePools.Count; i++)
					{
						McsUtility.Models.WalletsModel infoPool = infoCurrency.OrePools[i];
						infosPool.Add(new Models.AddressModel
						{
							Number = (i + 1).ToString(),
							CurrencyName = infoCurrency.Remark,
							Address = infoPool.Address,
							Remark = infoPool.Remark
						});
					}
				}
			}

			WalletList.DataSource = infosWallet;
			PoolList.DataSource = infosPool;
		}

		#endregion



		#region void LoadData() 读取并显示数据。

		private delegate void DelegeteLoadData();

		/// <summary>
		/// 读取并显示数据。
		/// </summary>
		private void LoadData()
		{
			if (CurrencyList.InvokeRequired)
			{
				DelegeteLoadData d = new DelegeteLoadData(LoadData);
				this.BeginInvoke(d);
			}
			else
			{
				List<Models.CurrencyModel> infosCurrency = new List<Models.CurrencyModel>();
				List<Models.AddressModel> infosWallet = new List<Models.AddressModel>();
				List<Models.AddressModel> infosPool = new List<Models.AddressModel>();

				int walletNumber = 1;
				int poolNumber = 1;
				for (int i = 0; i < Common.Data.UserCurrency.Count; i++)
				{
					McsUtility.Models.CurrencysModel infoCurrency = Common.Data.UserCurrency[i];
					infosCurrency.Add(new Models.CurrencyModel
					{
						Id = infoCurrency.ID,
						Number = (i + 1).ToString(),
						Name = infoCurrency.Name
					});

					if (this.SelectedCurrencyId == 0 || infoCurrency.ID == this.SelectedCurrencyId)
					{
						for (int j = 0; j < infoCurrency.Wallets.Count; j++)
						{
							McsUtility.Models.WalletsModel infoWallet = infoCurrency.Wallets[j];
							infosWallet.Add(new Models.AddressModel
							{
								Id = infoWallet.ID,
								Number = walletNumber.ToString(),
								CurrencyName = infoCurrency.Remark,
								Address = infoWallet.Address,
								Remark = infoWallet.Remark
							});
							walletNumber++;
						}

						for (int j = 0; j < infoCurrency.OrePools.Count; j++)
						{
							McsUtility.Models.WalletsModel infoPool = infoCurrency.OrePools[j];
							infosPool.Add(new Models.AddressModel
							{
								Id = infoPool.ID,
								Number = poolNumber.ToString(),
								CurrencyName = infoCurrency.Remark,
								Address = infoPool.Address,
								Remark = infoPool.Remark
							});
							poolNumber++;
						}
					}
				}

				CurrencyList.DataSource = infosCurrency;
				WalletList.DataSource = infosWallet;
				PoolList.DataSource = infosPool;

				int currencySelectedIndex = infosCurrency.FindIndex(p => p.Id == this.SelectedCurrencyId);
				CurrencyListGridView.FocusedRowHandle = currencySelectedIndex;
			}
		}

		#endregion

		#region void RequestRefresh() 请求刷新数据。

		/// <summary>
		/// 请求刷新数据。
		/// </summary>
		private void RequestRefresh()
		{
			//发送数据
			if (this.Agent.IsStarted)
			{
				byte[] bytes = ProtocolHelper.WritePackage(ProtoType.MinerManagerGetCurrencysInfo, "");
				this.Agent.AgentSend(bytes);
			}
			else
			{
				if (MessageBox.Show("与服务器的链接断开，请重新登录系统。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
					Utility.Forms.FormClose(this);
			}
		}

		#endregion

		#region void RefreshEventArgs(object sender, EventArgs e) 执行刷新的事件。

		/// <summary>
		/// 执行刷新的事件。
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void RefreshEventArgs(object sender, EventArgs e)
		{
			RequestRefresh();
		}

		#endregion
	}
}